<?php


namespace ChainOfResponsibilities\Account;


abstract class Account
{
    protected $successor;
    protected $balance;

    //下一个付款账户
    public function setNext(Account $account)
    {
        $this->successor = $account;
    }

    //付款
    public function pay(float $amountToPay)
    {
        //能付款
        if ($this->canPay($amountToPay)) {
            echo sprintf('Paid %s using %s' . PHP_EOL, $amountToPay, get_called_class());
        } elseif ($this->successor) {
            //不能付款，但是由下一个账户
            echo sprintf('Cannot pay using %s. Proceeding ..' . PHP_EOL, get_called_class());
            //让下一个账户付款
            $this->successor->pay($amountToPay);
        } else {
            //没有钱付款，而且没有下一个账户
            throw new \Exception('None of the accounts have enough balance');
        }
    }

    //判断余额是否够支付钱
    public function canPay($amount): bool
    {
        return $this->balance >= $amount;
    }
}